/*
 * @(#)SmartCommonBaseAction.java $version 2011. 10. 14
 * 
 * Copyright 2011 NHN Corp. All rights Reserved.
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hangame.mbl.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections15.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hangame.mbl.bo.BannerBO;
import com.hangame.mbl.bo.feed.FeedBO;
import com.hangame.mbl.bo.game.GameBO;
import com.hangame.mbl.bo.notice.NoticeBO;
import com.hangame.mbl.bo.review.ReviewBO;
import com.hangame.mbl.constant.CommonConst;
import com.hangame.mbl.model.Banner;
import com.hangame.mbl.model.Feed;
import com.hangame.mbl.model.Game;
import com.hangame.mbl.model.GameList;
import com.hangame.mbl.model.GameSimpleInfo;
import com.hangame.mbl.model.HspUserInfo;
import com.hangame.mbl.model.InstallInfo;
import com.hangame.mbl.model.Review;
import com.hangame.mbl.model.notice.Notice;
import com.hangame.mbl.util.CommonUtil;
import com.hangame.mbl.util.HspUserInfoUtil;

import com.nhncorp.lucy.web.metadata.Inject;
import com.nhncorp.pagination.taglib.PaginationInfo;

// TODO: Auto-generated Javadoc
/**
 * The Class SmartCommonBaseAction.
 * 
 * @author khpark
 */
public class SmartCommonBaseAction extends SmartPortalAction {
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -6738048765361995724L;
	
	/** The log. */
	private static Log log = LogFactory.getLog(SmartCommonBaseAction.class);

	/** The my profile. */
	private String myProfile = "";
	
	/** The my nick. */
	private String myNick = "";

	/** The has noti without reco game. */
	private boolean hasNotiWithoutRecoGame = false; //화면 우측에 공지를 보여줄지 여부. 추천게임은 안보여주고.

	/** The game bo. */
	protected GameBO gameBO;
	
	/** The banner bo. */
	protected BannerBO bannerBO;
	
	/** The review bo. */
	protected ReviewBO reviewBO;
	
	/** The feed bo. */
	protected FeedBO feedBO;
	
	/** The notice bo. */
	protected NoticeBO noticeBO;

	/**
	 * Sets the game bo.
	 * 
	 * @param gameBO the new game bo
	 */
	@Inject(beanId = "gameBO")
	public void setGameBO(GameBO gameBO) {
		this.gameBO = gameBO;
	}

	/**
	 * Sets the banner bo.
	 * 
	 * @param bannerBO the new banner bo
	 */
	@Inject(beanId = "bannerBO")
	public void setBannerBO(BannerBO bannerBO) {
		this.bannerBO = bannerBO;
	}

	/**
	 * Sets the review bo.
	 * 
	 * @param reviewBO the new review bo
	 */
	@Inject(beanId = "reviewBO")
	public void setReviewBO(ReviewBO reviewBO) {
		this.reviewBO = reviewBO;
	}

	/**
	 * Sets the feed bo.
	 * 
	 * @param feedBO the new feed bo
	 */
	@Inject(beanId = "feedBO")
	public void setFeedBO(FeedBO feedBO) {
		this.feedBO = feedBO;
	}

	/**
	 * Sets the notice bo.
	 * 
	 * @param noticeBO the new notice bo
	 */
	@Inject(beanId = "noticeBO")
	public void setNoticeBO(NoticeBO noticeBO) {
		this.noticeBO = noticeBO;
	}

	/* (non-Javadoc)
	 * @see com.hangame.mbl.action.SmartPortalAction#init()
	 */
	@Override
	public String init() throws Exception {
		//공통 우측 이벤트 베너 : CommonConst.BANNER_LOC_RIGHTEVENT		
		List<Banner> bannerRightEventList = bannerBO.getBannerList(CommonConst.BANNER_LOC_RIGHTEVENT);
		setAttribute("bannerRightEventList", bannerRightEventList);

		//공통 추천게임 리스트
		List<GameList> recommendGameList = gameBO.getRecommendGameList();
		setAttribute("recommendGameList", recommendGameList);

		setAllgameSimpleList(); // 모든 게임(간단정보) 리스트
		setAttribute("hasNotiWithoutRecoGame", this.hasNotiWithoutRecoGame); //화면 우측에 공지를 보여줄지 여부. 추천게임은 안보여주고.

		return super.init();
	}

	/**
	 * 게임정보 setAttribute.
	 * 
	 * @param gameNo the game no
	 * @return true, if successful
	 */
	protected boolean setGameInfo(int gameNo) {
		Game game = this.gameBO.getGameDetailInfo(gameNo);
		
		if (game.getGameNo() == -1) {
			return false;
		}
		
		List<GameList> rGameList = game.getRelatedGameList();
		if (rGameList != null && rGameList.size() > 3) { //관련게임 랜덤하게 3개 가져와 set함
			Collections.shuffle(rGameList); //shuffle
			rGameList = rGameList.subList(0, 3); //3개 가져옴
			game.setRelatedGameList(rGameList);
		}

		// 게임상세 배너.
		List<Banner> gameDetailBannerList = bannerBO.getGameDetailBannerList(CommonConst.BNNRLINK_GAMEDTL_H, gameNo);
		
		setAttribute("gameDetailBannerList", gameDetailBannerList);
		
		String gameMovieUrl = game.getGameMovieUrl();
		if (gameMovieUrl != null && !"".equals(gameMovieUrl)) {
			String gameMobileMovieUrl = gameMovieUrl.substring(0, gameMovieUrl.length() - 3) + "mp4";
			game.setGameMobileMovieUrl(gameMobileMovieUrl);
		}
		
		setAttribute("game", game);

		setAttribute("hasMovie", StringUtils.isNotEmpty(game.getGameMovieUrl())); //동영상 있는지 여부
		setAttribute("hasScreenShot", game.getScreenShotList() != null && game.getScreenShotList().size() > 0); //스크릿샷 있는지 여부

		setHasMarketBtn(game.getInstallInfoList());
		
		setAttribute("facebookDescription", game.getSimpleDescription() + " " + game.getRedirectUrl());
		return true;
	}	
	
	/**
	 * 해당 게임이 등록된 마켓들의 has 정보를 setAttribute 해준다.
	 * 
	 * @param istInfo the new checks for market btn
	 */
	protected void setHasMarketBtn(List<InstallInfo> istInfo) {
		//앱스토어, 티스토어, 올레마켓, 안드로이드 마켓, OZ스토어, 모토로이마켓
		String[] marketNames = {"APPSTORE", "TSTORE", "OLLEHSTORE", "ANDSTORE", "OZSTORE", "HANGAME"}; //TODO 
		String[] marketType = {"KA", "KS", "KT", "KG", "KL", "KH"};
		boolean hasAndroidMarket = false;

		if (istInfo != null && istInfo.size() > 0) {
			for (int i = 0; i < marketNames.length; i++) {
				for (InstallInfo info : istInfo) {
					if (StringUtils.equals(marketType[i], info.getMarket())) {
						setAttribute("HAS_BTN_" + marketNames[i], "true");
						setAttribute("MARKET_URL_" + marketNames[i], info.getUrl());
						if (!hasAndroidMarket && i > 0) { //안드로이드 마켓을 가지고있는지 여부. 배열에서 1번부터가 안드로이드마켓
							hasAndroidMarket = true;
							setAttribute("HAS_ANDROID_MARKET", hasAndroidMarket);
						}
						break;
					}
				}
			}
		}
	}

	/**
	 * 모든 게임목록을 setAttribute 해 줌.
	 */
	protected void setAllgameSimpleList() {
		int gameNo = NumberUtils.toInt(params.getString("gameNo"), 0);
		// 게임 상단 게임명 리스트
		ArrayList<GameSimpleInfo> allGameSimpleList = gameBO.getAllGameSimpleList();
		for (GameSimpleInfo gameSimpleInfo : allGameSimpleList) {
			if (gameSimpleInfo.getGameNo() == gameNo) {
				setAttribute("gameSimpleInfo", gameSimpleInfo);
				break;
			}
		}

		setAttribute("allGameSimpleList", allGameSimpleList);
	}

	/**
	 * 리뷰리스트 setAttribute.
	 */
	protected void setReviewList() {
		int gameNo = NumberUtils.toInt(params.getString("gameNo"), 0);
		int page = NumberUtils.toInt(params.getString("page"), 1);

		int reviewCount = reviewBO.getReviewCount(gameNo);
		PaginationInfo paginationInfo = new PaginationInfo("default", request, reviewCount);
		int offset = CommonUtil.calcOffset(page, paginationInfo.getPageSize());

		ArrayList<Review> reviewList = new ArrayList<Review>();
		reviewList = reviewBO.getReviewList(gameNo, offset, paginationInfo.getPageSize());

		setAttribute("paginationInfo", paginationInfo);
		setAttribute("reviewList", reviewList);
	}

	/**
	 * 게임피드 리스트 setAttribute.
	 */
	protected void setFeedList() {
		// 필요 기본 정보 파라미터 
		int gameNo = NumberUtils.toInt(params.getString("gameNo"), 0); // 전체게임 일때. gameNo = 0으로 처리.
		String isMyFeed = StringUtils.defaultIfEmpty(params.getString("isMyFeed"), "N");
		setAttribute("gameNo", gameNo);
		setAttribute("isMyFeed", isMyFeed);

		String userId = getUser().getUserId(); // 로그인시, 사용될 데이터 -> 비 로그인시, null값 들어감.

		// 페이지 네비게이션 에 필요한 Info
		int page = NumberUtils.toInt(params.getString("page"), 1);
		int feedListCount = feedBO.getFeedListCount(gameNo, userId, isMyFeed);
		PaginationInfo paginationInfo = new PaginationInfo("default", request, feedListCount);
		int pageSize = paginationInfo.getPageSize();
		int offset = CommonUtil.calcOffset(page, pageSize);
		setAttribute("paginationInfo", paginationInfo);

		// Feed 등록 폼에서 사용될 HSP에서 넘겨받을 로그인 된 profile 및 별명 정보 셋팅
		if (!StringUtils.isEmpty(userId)) {
			Map<String, String> userIdMap = new HashedMap<String, String>();
			userIdMap.put(userId, userId);
			Map<String, HspUserInfo> hspUserInfoMap = HspUserInfoUtil.getHspUserInfo(userIdMap);

			if (hspUserInfoMap != null) {
				HspUserInfo hspUserInfo = hspUserInfoMap.get(userId);
				if (hspUserInfo != null) {
					setMyProfile(CommonConst.MPHOTO_PREFIX_URL + hspUserInfoMap.get(userId).getsNo() + CommonConst.MPHOTO_SUFFIX_URL);
					setMyNick(hspUserInfoMap.get(userId).getNickName());
				} else {
					setMyProfile(CommonConst.MPHOTO_PREFIX_URL + 0 + CommonConst.MPHOTO_SUFFIX_URL);
					setMyNick("");
				}
			}

		} else {
			setMyProfile("");
			setMyNick("");
		}

		log.debug("getMyProfile======" + getMyProfile());
		log.debug("getMyNick=========" + getMyNick());

		// 게임피드 리스트
		List<Feed> feedList = feedBO.getFeedList(gameNo, offset, pageSize, userId, isMyFeed);
		setAttribute("feedList", feedList);
	}

	/**
	 * 화면우측 공지목록 3개 setAttribute.
	 */
	protected void setLatestNoticeList() {
		List<Notice> latestNoticeList = this.noticeBO.getNoticeList(0, 3);
		if (latestNoticeList != null && latestNoticeList.size() > 0) {
			if (latestNoticeList.size() > 3) {
				latestNoticeList = latestNoticeList.subList(0, 3);	
			}
			setAttribute("latestNoticeList", latestNoticeList);
		}
	}

	/**
	 * Gets the my profile.
	 * 
	 * @return the my profile
	 */
	public String getMyProfile() {
		return myProfile;
	}

	/**
	 * Sets the my profile.
	 * 
	 * @param myProfile the new my profile
	 */
	public void setMyProfile(String myProfile) {
		this.myProfile = myProfile;
	}

	/**
	 * Gets the my nick.
	 * 
	 * @return the my nick
	 */
	public String getMyNick() {
		return myNick;
	}

	/**
	 * Sets the my nick.
	 * 
	 * @param myNick the new my nick
	 */
	public void setMyNick(String myNick) {
		this.myNick = myNick;
	}

	/**
	 * Sets the checks for noti without reco game.
	 * 
	 * @param hasNotiWithoutRecoGame the new checks for noti without reco game
	 */
	public void setHasNotiWithoutRecoGame(boolean hasNotiWithoutRecoGame) {
		this.hasNotiWithoutRecoGame = hasNotiWithoutRecoGame;
	}

	/**
	 * Gets the checks for noti without reco game.
	 * 
	 * @return the checks for noti without reco game
	 */
	public boolean getHasNotiWithoutRecoGame() {
		return hasNotiWithoutRecoGame;
	}

}
